﻿using System.Collections.Generic;
using System.Linq;
using Fujitsu.JiraAnalysis.DAL;
using Fujitsu.JiraAnalysis.TrackingSystemAdapter;
using Fujitsu.JiraAnalysis.ReplicationService.SynchronizeExceptions;
using Fujitsu.JiraAnalysis.JiraRPC;

namespace Fujitsu.JiraAnalysis.ReplicationService.Synchronize
{
    public class IssueStatusSync: SyncBase<RemoteStatus, StatusMapping>
    {
        StatusStorage statusStorage = new StatusStorage();

        protected override SyncException GetSyncException(string projectName, int projectId, string projectKey)
        {
            return new IssueStatusSyncException(projectName, projectId, projectKey);
        }

        protected override List<StatusMapping> GetStorageItems(int projectId)
        {
            return statusStorage.GetStatuses(projectId);
        }

        protected override List<RemoteStatus> GetTrackSystemInfoItems(Project project, ITrackSystemInfo adapter)
        {
            return adapter.GetStatuses();
        }

        protected override StatusMapping FindMatchInStorage(List<StatusMapping> storageItems, RemoteStatus trackSystemInfoItem, int projectId)
        {
            return storageItems.FirstOrDefault(i => i.JiraStatusID.ToString() == trackSystemInfoItem.id && i.ProjectID == projectId);
        }

        protected override void Update(RemoteStatus trackSystemItem, StatusMapping statusMapping)
        {
            if (statusMapping.Name == trackSystemItem.name) 
                return;
            statusStorage.UpdateStatusName(statusMapping.ProjectID, statusMapping.JiraStatusID, trackSystemItem.name);
        }
    }
}
